package com.fingard.dsp.bank.directbank.zjtlcb02.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    private static final String SIGN_SHA = "SHA";
    private static final String SIGN_SHA256 = "SHA-256";
    private static final String SIGN_SHA512 = "SHA-512";
    private static final String SIGN_MD5 = "MD5";

    private static char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public static String md5(String str, String signType) {
        MessageDigest sign = null;
        try {
            if (SIGN_MD5.equalsIgnoreCase(signType)) {
                sign = MessageDigest.getInstance(SIGN_MD5);
            } else if (SIGN_SHA.equalsIgnoreCase(signType)) {
                sign = MessageDigest.getInstance(SIGN_SHA);
            } else if (SIGN_SHA256.equalsIgnoreCase(signType)) {
                sign = MessageDigest.getInstance(SIGN_SHA256);
            } else if (SIGN_SHA512.equalsIgnoreCase(signType)) {
                sign = MessageDigest.getInstance(SIGN_SHA512);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        if (sign != null) {
            try {
                sign.update(str.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            byte[] encodeBytes = sign.digest();
            char encodeStr[] = new char[encodeBytes.length * 2];
            int k = 0;
            for (int i = 0; i < encodeBytes.length; i++) {
                byte encodeByte = encodeBytes[i];
                encodeStr[k++] = hexDigits[encodeByte >> 4 & 0xf];
                encodeStr[k++] = hexDigits[encodeByte & 0xf];
            }
            return new String(encodeStr).toUpperCase();
        }
        return null;
    }

    public static String md5_(String str) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");

            if (md5 != null) {
                md5.update(str.getBytes("utf-8"));
                byte[] encodeBytes = md5.digest();
                char encodeStr[] = new char[encodeBytes.length * 2];
                int k = 0;
                for (int i = 0; i < encodeBytes.length; i++) {
                    byte encodeByte = encodeBytes[i];
                    encodeStr[k++] = hexDigits[encodeByte >> 4 & 0xf];
                    encodeStr[k++] = hexDigits[encodeByte & 0xf];
                }
                return new String(encodeStr).toUpperCase();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
